package com.yao2san.simcasclient.config;

import com.yao2san.sim.framework.utils.BeanContextUtil;
import com.yao2san.simcasclient.authentication.basics.filter.SimCasBasicsFilter;
import com.yao2san.simcasclient.authentication.oauth.filter.SimCasOauthFilter;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * sim cas auto configuration
 */
@ConfigurationProperties(prefix = "sim.cas")
@EnableConfigurationProperties(SimCasAutoConfiguration.class)
public class SimCasAutoConfiguration {
    /**
     * authentication type:
     * basics: use cas1.0 protocol
     * oauth: use OAuth2.0 protocol
     * default is basics
     */
    @Getter
    @Setter
    private String type = "basics";

    @Bean
    public ClientConfig clientConfig() {
        return new ClientConfig();
    }

    @Bean
    public ServerConfig serverConfig() {
        return new ServerConfig();
    }

    @Bean
    @ConditionalOnProperty(prefix = "sim.cas", name = "type", havingValue = "basics")
    public FilterRegistrationBean simCasBasicsFilter(ClientConfig clientConfig, ServerConfig serverConfig) {
        FilterRegistrationBean<SimCasBasicsFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new SimCasBasicsFilter(clientConfig, serverConfig));
        List<String> urlIncludes = clientConfig.getUrlIncludes();
        String[] urlPatterns = new String[urlIncludes.size()];
        urlIncludes.toArray(urlPatterns);
        bean.addUrlPatterns(urlPatterns);
        bean.setOrder(0);
        return bean;
    }

    @Bean
    @ConditionalOnProperty(prefix = "sim.cas", name = "type", havingValue = "oauth")
    public FilterRegistrationBean simCasOauthFilter(ClientConfig clientConfig, ServerConfig serverConfig) {
        FilterRegistrationBean<SimCasOauthFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new SimCasOauthFilter(clientConfig, serverConfig));
        List<String> urlIncludes = clientConfig.getUrlIncludes();
        String[] urlPatterns = new String[urlIncludes.size()];
        urlIncludes.toArray(urlPatterns);
        bean.addUrlPatterns(urlPatterns);
        bean.setOrder(0);
        return bean;
    }
}
